package com.bite.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.security.handler.ServiceException;
import com.bit.common.security.service.TokenService;
import com.bite.common.core.contants.HttpConstants;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.core.domain.vo.LoginUserVO;
import com.bite.system.domain.sysuser.SysUser;
import com.bite.system.domain.sysuser.dto.SysUserSaveDIO;
import com.bite.system.mapper.sysuser.SysUserMapper;
import com.bite.system.service.sysuser.ISystemService;
import com.bite.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RefreshScope
public class SystemServiceImpl implements ISystemService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_sys_user where user_account = #{userAccount}
        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper
                .select(SysUser::getPassword,SysUser::getUserId,SysUser::getNickName).eq(SysUser::getUserAccount,userAccount));
        //R loginResult = new R();
        if (sysUser == null){
//            loginResult.setCode(ResultCode.FAILED_USER_NOT_EXISTS.getCode());
//            loginResult.setMsg(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());
//            return loginResult;
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password,sysUser.getPassword())){
//            loginResult.setCode(ResultCode.SUCCESS.getCode());
//            loginResult.setMsg(ResultCode.SUCCESS.getMsg());
//            return loginResult;
            //生成token
//            Map<String,Object> claims = new HashMap<>();
//            String userKey = UUID.fastUUID().toString();
//
//            claims.put(JwtConstants.LOGIN_USER_ID,sysUser.getUserId());
//            claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
//            String token = JwtUtils.createToken(claims, secret);
//            //第三方机制中存储敏感信息-redis 表明用户身份的字段--identity
//            //Integer identity = 1;  //1-普通用户 2-管理员用户  对象-可拓展
//
//            //身份认证具体要存储哪些
//            //使用什么样的数据结构 key value String hash 单个单个进行,不需要存一组的结构list zset set
//            //没有必要使用hash,String高效性即可,因为前面设置了序列化器
//            //key 必须保证唯一,    便于维护  统一的前缀  logintoken:userId 通过雪花算法生成的唯一主键
//            String key = CacheConstants.LOGIN_TOKEN_KEY +userKey;
//            LoginUser loginUser = new LoginUser();
//            loginUser.setIdentity(UserIdentity.ADMIN.getValue());
//            //jwt过期时间怎么记录,定为多长   720min 2-3小时
//            redisService.setCacheObject(key,loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
            //判断token是否过期-通过redis
            return R.ok(tokenService.createToken(sysUser.getUserId(),
                    secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null));

        }
//        loginResult.setCode(ResultCode.FAILED_LOGIN.getCode());
//        loginResult.setMsg(ResultCode.FAILED_LOGIN.getMsg());
//        return loginResult;
        return R.fail(ResultCode.FAILED_LOGIN);
        //通过账号在数据库查询,对应的用户信息

    }


    /**
     * 用户退出
     * @param token
     * @return
     */
    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token,secret);
    }


    /**
     * 添加管理员用户
     * @param sysUserSaveDIO
     * @return
     */
    @Override
    public int add(SysUserSaveDIO sysUserSaveDIO) {
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount,sysUserSaveDIO.getUserAccount()));

        if (CollectionUtil.isNotEmpty(sysUserList)){
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDIO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDIO.getPassword()));
        return sysUserMapper.insert(sysUser);

    }


    /**
     * 获取用户当前信息-查看管理员昵称
     * @param token
     * @return
     */
    @Override
    public R<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token,secret);
        if (loginUser == null){
            return R.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return R.ok(loginUserVO);
    }






}
